package xyz.jcat.sat.gateway;

import cn.dev33.satoken.id.SaIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

@Slf4j
@Component
public class ForwardAuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("come in ForwardAuthFilter");
        Consumer<HttpHeaders> headers = httpHeader -> {
            httpHeader.set(SaIdUtil.ID_TOKEN, SaIdUtil.getToken());
        };
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(headers).build();
        exchange = exchange.mutate().request(serverHttpRequest).build();
        return chain.filter(exchange);
    }

}
